package com.dkm.nettysocketdemo.myWebsite.action;

import com.dkm.nettysocketdemo.myWebsite.domain.HelmetClient;
import com.dkm.nettysocketdemo.myWebsite.domain.HelmetUser;
import com.dkm.nettysocketdemo.myWebsite.service.HelmetClientService;
import com.dkm.nettysocketdemo.untils.Message;
import com.dkm.nettysocketdemo.untils.Tools;
import com.dkm.nettysocketdemo.untils.jwt.intertfaceceptor.domain.LocalUser;
import com.dkm.nettysocketdemo.untils.jwt.jwtutils.TokenUtil;
import com.dkm.nettysocketdemo.untils.jwt.login.UserLoginToken;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;

/**
 * @ClassName : MyUserAction  //类名
 * @Description : 客户服务Action  //描述
 * @Author : shizhicheng//作者
 * @Date: 2021-04-01 11:42  //时间
 */
@RestController
@RequestMapping("HelmetClientAction")
public class HelmetClientAction {


    /**
     * 用户服务接口
     */
    @Resource
    HelmetClientService clientService;


    /**
     * token数据中的个人信息
     */
    @Resource
    LocalUser localUser;
    /**
     *  后台登陆人
      */
    HelmetUser helmetUser;

    /**
     * 获取个人信息
     *
     * @return 个人信息
     */
    @GetMapping("getUser")
    @UserLoginToken
    public Message getUser() {
        Message message = new Message();
        message.setCode(200);
        HelmetClient user = localUser.getUser();
        message.setData(user);
        message.setMsg("获取用户信息成功");
        return message;
    }

    /**
     * 登录
     *
     * @param userAccountNumber 用户名
     * @param userPwd           密码
     * @return 回调函数
     */
    @GetMapping("isLogin")
    public Message isLogin(String userAccountNumber, String userPwd) {
        HelmetClient user = clientService.isLogin(userAccountNumber, userPwd);
        Message message = new Message();
        message.setCode(200);
        if (ObjectUtils.isEmpty(user)) {
            message.setData(0);
            message.setMsg("账号密码错误");
        } else {
            String token = TokenUtil.createJwtToken(user);
            message.setData(token);
            message.setMsg("登录成功");
        }
        return message;
    }

    /**
     * 新增
     *
     * @param user 用户对象
     * @return 回调函数
     */
    /*@PostMapping("addUser")
    public Message addUser(MyUser user) throws IOException {
        if (user.getFileOne().getOriginalFilename() != null && !"".equals(user.getFileOne().getOriginalFilename())) {
            String path = fileTools.saveFile("head", user.getFileOne());
            user.setUserHeadPortrait(path);
        }
        int row = clientService.insert(user);
        Message message = new Message();
        message.setData(row);
        message.setCode(200);
        if (row == 1) {
            message.setMsg("新增成功");
        } else {
            message.setMsg("新增失败");
        }
        return message;
    }*/

    /**
     * 账户验证
     *
     * @param userId 账户id
     * @return 回调函数
     */
    /*@GetMapping("mailVerify/{userId}")
    public Message mailVerify(@PathVariable(value = "userId") String userId) {
        int row = clientService.mailVerify(userId);
        Message message = new Message();
        message.setData(row);
        message.setCode(200);
        if (row == 1) {
            message.setMsg("验证成功");
        } else {
            message.setMsg("验证失败");
        }
        return message;
    }*/

    /**
     * 修改名称
     *
     * @param userName 用户名称
     * @return 回调函数
     */
    @GetMapping("updateName")
    @UserLoginToken
    public Message updateName(String userName) {
        Message message = new Message();
        message.setCode(200);
        HelmetClient user = localUser.getUser();
        user.setClientName(userName);
        int row = clientService.update(user);
        if (row == 1) {
            message.setMsg("修改成功");
        } else {
            message.setMsg("修改失败");
        }
        message.setData(row);
        return message;
    }

    /**
     * fileOne
     *
     * @param file 文件地址
     * @return 回调函数
     */
    @PostMapping("updateFile")
    @UserLoginToken
    public Message updateFile(@RequestBody MultipartFile file) throws IOException {
        //MultipartFile file = BASE64DecodedMultipartFile.base64ToMultipart(fileOne);
        Message message = new Message();
        HelmetClient user = localUser.getUser();
        user.setClientHeadPortraitFile(file);
        String path = clientService.updateFile(user);
        message.setData(path);
        message.setCode(200);
        message.setMsg("修改成功");
        return message;
    }

    /**
     * 邮箱判断
     *
     * @param mail 邮箱
     * @return 回调信息
     */
    /*@GetMapping("getMail/{mail}")
    public Message getMail(@PathVariable(value = "mail") String mail) {
        Message message = new Message();
        MyUser user = clientService.getMail(mail);
        message.setCode(200);
        if (ObjectUtils.isEmpty(user)) {
            message.setMsg("未曾注册过");
        } else {
            message.setData(user);
            message.setMsg("已注册");
        }
        return message;
    }*/

    /**
     * 修改邮箱
     *
     * @param userEmail 邮箱
     * @return 回调信息
     */
    @GetMapping("updateEmail")
    @UserLoginToken
    public Message updateEmail(String userEmail) {
        Message message = new Message();
        HelmetClient user = localUser.getUser();
        user.setClientMail(userEmail);
        int row = clientService.update(user);
        message.setCode(200);
        if (row == 1) {
            message.setMsg("修改邮箱成功");
        } else {
            message.setMsg("修改邮箱失败");
        }

        return message;
    }

    /**
     * 修改密码
     *
     * @param newUserPwd     新密码
     * @param oldUserPwd     旧密码
     * @param confirmUserPwd 确认密码
     * @return 回调信息
     */
    @GetMapping("updatePwd")
    @UserLoginToken
    public Message updatePwd(String newUserPwd, String oldUserPwd, String confirmUserPwd) {
        Message message = new Message();
        HelmetClient user = clientService.findById(localUser.getUser().getPkClientId());
        if (user.getClientPwd().equals(Tools.password(oldUserPwd)) && confirmUserPwd.equals(newUserPwd)) {
            user.setClientPwd(newUserPwd);
            int row = clientService.update(user);
            if (row == 1) {
                message.setData(1);
                message.setMsg("修改成功");
            } else {
                message.setData(0);
                message.setMsg("修改失败");
            }
        } else {
            message.setData(0);
            message.setMsg("旧密码不正确或确认密码错误");
        }
        return message;
    }

    /**
     * 修改手机号
     *
     * @param userPhone 手机号
     * @return 回调函数
     */
    @GetMapping("updatePhone")
    @UserLoginToken
    public Message updatePhone(String userPhone) {
        Message message = new Message();
        message.setCode(200);
        HelmetClient user = localUser.getUser();
        user.setClientPhoneNumber(userPhone);
        int row = clientService.update(user);
        if (row == 1) {
            message.setMsg("修改成功");
        } else {
            message.setMsg("修改失败");
        }
        message.setData(row);
        return message;
    }



    @GetMapping("/findByIdHelmetClient/{pkClientId}")
    public Message findByIdHelmetClient(@PathVariable("pkClientId")String pkClientId){
        Message message = new Message();
        HelmetClient helmetClient = clientService.findById(pkClientId);
        message.setCode(200);
        message.setData(helmetClient);
        return message;
    }

    /**
     * 增加或者更新用户
     * @param helmetClient 用户
     * @param ids 用户
     * @param request 请求
      * @return Message
     */
    @PostMapping("insertOrUpdateHelmetClient")
    public Message insertHelmetClient (HelmetClient helmetClient,
                                       @RequestParam(value = "ids[]", required = false) String [] ids,HttpServletRequest request){
        rowMap(request);
        Message message = new Message();
        List<String> idss=null;
        String pwd=null;
        if (ids!=null){
            // 数组转换成集合
            idss= Arrays.asList(ids);
        }

        int row=0;
        // 判断用户id 是否为空，如果为空，则进入增加，反之，进入修改
        if(helmetClient.getPkClientId().isEmpty()){
            helmetClient.setCreatedBy(helmetUser.getUserName());
            pwd = Tools.getRandomString(6);
            helmetClient.setClientPwd(pwd);
            row = clientService.insert(helmetClient,idss);
        }else {
            helmetClient.setUpdatedBy(helmetUser.getUserName());
            row = clientService.updateMod(helmetClient,idss);
        }
        message.setCode(200);
        if (row>0) {
            message.setData(pwd);
            message.setCount(row);
            message.setMsg("操作成功");
        } else {
            message.setMsg("操作失败");
            message.setCount(0);
        }
        return message;
    }

    /**
     * 查询所有的用户(在后台)
     * @param helmetClient 用户
     * @param startTime  开始时间
     * @param endTime 结束时间
     * @param page 页数
     * @param limit 数量
     * @return Message
     */
    @GetMapping("selectAllHelmetClient")
    public Message selectAllHelmetClient(HelmetClient helmetClient,String startTime,String endTime,Integer page,Integer limit){
       Message message = new Message();
       List<HelmetClient> list = clientService.selectAllHelmetClient(helmetClient,startTime,endTime,page,limit);
       Integer rowCount = clientService.rowCount(helmetClient,startTime,endTime);
       message.setCount(rowCount);
       message.setCode(0);
       message.setData(list);
       return message;
   }

    /**
     * 根据用户id 删除
     * @param pkClientId 用户id
     * @return Message
     */
    @PostMapping("DeleteByIdHelmetClient/{pkClientId}")
    public Message  deleteByIdHelmetClient(@PathVariable("pkClientId") String pkClientId){
        Message message=new Message();
        int row = clientService.deleteById(pkClientId);
        message.setCode(200);
        if (row>0){
            message.setCount(row);
            message.setData("删除成功");
            return message;
        }else {
            message.setCount(row);
            message.setData("删除失败");
            return message;
        }
    }

    /**
     * 批量删除
     * @param ids 用户id
     * @return Message
     */
    @PostMapping("deleteAllHelmetClient")
    public Message deleteAllHelmetClient(@RequestParam(value = "ids[]", required = false) String[] ids,HttpServletRequest request){
        rowMap(request);
        Message message=new Message();
        List<String> idssi = null;
        //id为空的情况下
        if (ObjectUtils.isEmpty(ids)) {
            message.setMsg("操作失败");
            message.setCode(0);
        } else {
            idssi = Arrays.asList(ids);
        }
        int row = clientService.deleteAll(idssi,helmetUser.getUserName());
        if (row>0){
            message.setMsg("操作成功");
            message.setCode(200);
            message.setCount(row);
        }else {
            message.setMsg("操作失败");
            message.setCode(0);
        }
        return  message;
    }

    /**
     * 查询用户账号是否重名
     * @param clientAccountNumber 用户账号
     * @param pkClientId 用户id
     * @return Message
     */
    @GetMapping("/clientSelectCount")
    public Message selectCount(String clientAccountNumber,String pkClientId){
        Message message=new Message();
        Integer count = clientService.selectCount(clientAccountNumber, pkClientId);
        message.setCode(200);
        message.setData(count);
        return  message;
    }
    /**
     * 简化代码
     *
     * @param request 请求
     */
    private void rowMap(HttpServletRequest request) {
        helmetUser = (HelmetUser) request.getSession().getAttribute("user");
    }
}
